﻿using System;
using System.Linq.Expressions;
using Medora.DataContract;
using Medora.Model.Persons;
using Medora.Services.Utils;

namespace Medora.Services.Persons
{
    public class PersonsService:ServiceBase<Person, PersonFilter>, IPersonsService
    {
        public PersonsService(IUow uow, IUserService userService, IFilterConstructor<PersonFilter, Person> filterConstructor) : base(uow, userService, filterConstructor)
        {
            _repository = _uow.Persons;
        }

        protected override Expression<Func<Person, bool>> ConstructFilter(Expression<Func<Person, bool>> startE, PersonFilter filter)
        {
            if (filter == null) return startE;

            var finalE = startE;

            if (filter.BirthYear.HasValue)
            {
                Expression<Func<Person, bool>> fExpression =
                    o => o.DateBirth.Value.Year == filter.BirthYear;
                finalE = _filterConstructor.And(finalE, fExpression);
            }

            if (!string.IsNullOrEmpty(filter.FirstName))
            {
                Expression<Func<Person, bool>> fExpression =
                    o => o.FirstName.Contains(filter.FirstName);
                finalE = _filterConstructor.And(finalE, fExpression);
            }

            if (!string.IsNullOrEmpty(filter.LastName))
            {
                Expression<Func<Person, bool>> fExpression =
                    o => o.LastName.Contains(filter.LastName);
                finalE = _filterConstructor.And(finalE, fExpression);
            }

            if (!string.IsNullOrEmpty(filter.Idnp))
            {
                Expression<Func<Person, bool>> fExpression =
                    o => o.Idnp.Contains(filter.Idnp);
                finalE = _filterConstructor.And(finalE, fExpression);
            }
            return finalE;


        }
    }
}